package com.czf.testmodule.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;

import java.util.Calendar;
import java.util.HashMap;

/**
 * @author zfChen
 * @create 2022/5/5 13:59
 */
public class JwtTest {

    @Test
    public void testToken(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,30);

        String token = JWT.create()
                .withHeader(new HashMap<>())     // Header
                .withClaim("userId", 21)    // Payload
                .withClaim("userName", "czf")
                .withExpiresAt(calendar.getTime())  // 过期时间
                .sign(Algorithm.HMAC256("123456"));  // 签名用的secret

        System.out.println(token);
    }

    @Test
    public void testResolveToken(){
        // 创建解析对象，使用的算法和secret要与创建token时保持一致
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("123456")).build();
        // 解析指定的token
        DecodedJWT decodedJWT =
                jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6ImN6ZiIsImV4cCI6MTY1MTczMjAxNSwidXNlcklkIjoyMX0.xJTpfGy_CNSZCO1cyQ5vhQ19dYOgWcgE7R8egMN6AG0");
        // 获取解析后的token中的payload信息
        Claim userId = decodedJWT.getClaim("userId");
        Claim userName = decodedJWT.getClaim("userName");
        System.out.println(decodedJWT);
        System.out.println(userId.asInt());
        System.out.println(userName.asString());
        // 输出超时时间
        System.out.println(decodedJWT.getExpiresAt());
    }

}
